import { Flex, Form } from "antd"
import dayjs from "dayjs"
import { FC, useEffect, useState } from "react"
import { useSelector } from "react-redux"

import { PageType } from "@/api/business/types"
import { DataTypeTopupRecord } from "@/api/member/types"
import { IMemberParams } from "@/api/risk/types"
import { ResetButton, SearchButton, TableCodeInput } from "@/components/business"
import TimeRangePicker from "@/components/business/formItems/common/timeRangePicker"
import { DataList, QueryForm, SFormItem, Slot } from "@/components/common"
import { CardContainer } from "@/components/common/styled"
import StyleSelect from "@/components/common/styleSelect"
import { useApi, usePagination, usePermission } from "@/hooks"
import { useLocale } from "@/locales"
import { AppState } from "@/stores"
import { rangePastNDays } from "@/utils"

import { customShortcuts } from "../tableInfo"
import { TableInfoContainer } from "../tableInfo/styles"
import { columnsSquidInfo } from "./TableInfo"

const defaultParam = {
	registerTime: rangePastNDays(7)
}

export const SquidInfo: FC<{ data: IMemberParams }> = ({ data }) => {
	const [form] = Form.useForm<{}>()
	const hasPermissionAction = usePermission("90750103")
	const { formatMessage, newFormat } = useLocale()
	const { pagination, resetPagination, onPageChange } = usePagination(100)
	const [tableData, setTableData] = useState<DataTypeTopupRecord | null>(null)
	const { generalHttp, loading } = useApi()
	const { allDictLists } = useSelector((state: AppState) => state.config)

	const optionsSquidModels = allDictLists["squidModels"]
		? allDictLists["squidModels"].map((item: { label: string; value: any }) => {
				return {
					label: item.label,
					value: item.value
				}
		  })
		: []
	const optionsSquidSettleTypes = allDictLists["squidSettleTypes"]
		? allDictLists["squidSettleTypes"].map((item: { label: string; value: any }) => {
				return {
					label: item.label,
					value: item.value
				}
		  })
		: []
	const optionsGameType = allDictLists["gameType"]
		? allDictLists["gameType"].map((item: { label: string; value: any }) => {
				return {
					label: newFormat(item.label),
					value: item.value
				}
		  })
		: []
	const search = async (body: any, pageInfo?: PageType) => {
		const pageParams = pageInfo ? { ...pageInfo } : { ...pagination, pageNum: 1 }
		const bodySearchParam = {
			...defaultParam,
			...body,
			userName: data.userName,
			...(body.tableCode ? { tableCode: body.tableCode } : {}),
			...(body.squidModels ? { squidModels: body.squidModels } : {}),
			...(body.settleType ? { settleType: body.settleType } : {}),
			...(body.tableType ? { tableType: body.tableType } : {}),
			handBeginTimeTo: body.registerTime ? dayjs(body.registerTime[1]).format("YYYY-MM-DD HH:mm:ss") : "",
			handBeginTimeFrom: body.registerTime ? dayjs(body.registerTime[0]).format("YYYY-MM-DD HH:mm:ss") : "",
			...pageParams
		}
		delete bodySearchParam.registerTime
		const [err, dataSquidInfoRes] = await generalHttp<DataTypeTopupRecord>(
			"https://dxmerchant-fat.ak12.cc/dx-merchant-gateway/dx-game-data-manager/squidRoundData/getRoundPage",
			{
				...bodySearchParam
			}
		)
		if (!err) {
			if (!pageInfo) {
				resetPagination((pageInfo: PageType) => search(body, pageInfo))
			}

			setTableData(
				(dataSquidInfoRes as DataTypeTopupRecord) ?? {
					pageNum: 1,
					pageSize: pagination.pageSize,
					totalRecord: 0,
					record: []
				}
			)
		}
	}
	const resetQuery = () => {
		form.resetFields()
		form.submit()
	}

	useEffect(() => {
		form.submit()
	}, [])

	return (
		<TableInfoContainer>
			<CardContainer>
				<QueryForm form={form} onFinish={search} initialValues={defaultParam}>
					<Slot slotname="formItems">
						<TableCodeInput />
						<SFormItem name="tableType" label={formatMessage({ id: "dxn.card_ables_list.game_name" })}>
							<StyleSelect allowClear placeholder={formatMessage({ id: "common.select_all" })} options={optionsGameType} />
						</SFormItem>
						<SFormItem name="squidModel" label={formatMessage({ id: "member.squidModel" })}>
							<StyleSelect allowClear placeholder={formatMessage({ id: "label.select_all" })} options={optionsSquidModels} />
						</SFormItem>
						<SFormItem name="settleType" label={formatMessage({ id: "member.settleType" })}>
							<StyleSelect allowClear placeholder={formatMessage({ id: "label.select_all" })} options={optionsSquidSettleTypes} />
						</SFormItem>
						<TimeRangePicker shortcuts={customShortcuts(formatMessage)} allowClear={false} label="member.squid_time" />
					</Slot>
					<Slot slotname="buttons">
						<Flex gap={10}>
							<SearchButton htmlType="submit" loading={loading} />
							<ResetButton onClick={resetQuery} loading={loading} />
						</Flex>
					</Slot>
				</QueryForm>
			</CardContainer>

			<DataList
				maxHeight="400px"
				loading={loading}
				pagination={{
					current: tableData?.pageNum ?? 1,
					pageSize: tableData?.pageSize ?? 0,
					total: tableData?.totalRecord ?? 0,
					showSizeChanger: true,
					showTotal: (total: number) => `共  ${total}  条`
				}}
				columns={columnsSquidInfo(hasPermissionAction)}
				data={tableData?.record ?? []}
				onChange={onPageChange}
			/>
		</TableInfoContainer>
	)
}
